package com.platform.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.jfinal.aop.Duang;
import com.jfinal.kit.Prop;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.wxaapp.WxaConfig;
import com.jfinal.wxaapp.WxaConfigKit;
import com.jfinal.wxaapp.api.WxaTemplate;
import com.jfinal.wxaapp.api.WxaTemplateApi;
import com.platform.entity.OrderEntity;
import com.platform.entity.OrderGoodsEntity;
import com.platform.entity.ShippingEntity;
import com.platform.entity.UserEntity;
import com.platform.service.OrderGoodsService;
import com.platform.service.OrderService;
import com.platform.service.ShippingService;
import com.platform.service.UserService;
import com.platform.utils.*;
import com.platform.utils.excel.ExcelExport;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;


/**
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-13 10:41:09
 */
@RestController
@RequestMapping("order")
public class OrderController {

    String appid = "wx67f170383b0fc225";
    String partner = "1513549621";
    String paternerKey = "nttvYygWADqBrTcLxV2VpdIFcYTj4YCn";
    String refund_url = "https://shop.chunyajkkj.com/ch/api/pay/refund_notify";
    String certPath = ResourceUtil.getConfigByName("wx.certName");

    @Autowired
    private OrderService orderService;
    @Autowired
    private ShippingService shippingService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderGoodsService orderGoodsService;


    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("order:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<OrderEntity> orderList = orderService.queryList(query);

        if (orderList.size() > 0) {
            for (OrderEntity orderEntity : orderList) {
                Integer userId = orderEntity.getUserId();
                UserEntity userEntity = userService.queryObject(userId);
                if (userEntity != null) {
                    userEntity.setNickname(EmojiUtils.emojiRecovery2(userEntity.getNickname()));
                }
                orderEntity.setUserEntity(userEntity);
            }
        }

        int total = orderService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 导出excel
     */
    @RequestMapping("/export")
    @RequiresPermissions("order:export")
    public R export(@RequestParam String[] ids, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        params.put("ids", ids);

        //查询列表数据
        List<OrderEntity> orderList = orderService.queryList(params);

        ExcelExport ee = new ExcelExport("订单列表");

        String[] header = new String[]{
                "订单号", "会员微信昵称", "订单状态", "订单付款状态",
                "快递状态", "收货人", "收货地址", "联系电话",
                "快递公司", "快递单号", "快递费用", "实际支付",
                "订单总价", "商品总价", "下单时间", "发货时间",
                "支付时间", "申请退款日期", "订单确认收货日期", "购买商品",
                "买家留言", "卖家备注"};

        List<Map<String, Object>> list = new ArrayList<>();


        if (orderList.size() > 0) {
            for (OrderEntity orderEntity : orderList) {
                //订单号
                String orderSn = orderEntity.getOrderSn();
                //会员微信昵称
                Integer userId = orderEntity.getUserId();
                UserEntity userEntity = userService.queryObject(userId);
                //会员昵称
                String nickname = userEntity.getNickname();
                //订单状态
                String orderStatusText = orderEntity.getOrderStatusText();
                //订单付款状态
                String payStatusText = orderEntity.getPayStatusText();
                //快递状态
                String shippingStatusText = orderEntity.getShippingStatusText();
                //收货人
                String consignee = orderEntity.getConsignee();
                //收货地址
                String address = orderEntity.getAddress();
                //联系电话
                String mobile = orderEntity.getMobile();
                //快递公司
                String shippingName = orderEntity.getShippingName();
                //快递单号
                String shippingNo = orderEntity.getShippingNo();
                //快递费用
                BigDecimal shippingFee = orderEntity.getShippingFee();
                //实际支付
                BigDecimal actualPrice = orderEntity.getActualPrice();
                //订单总价
                BigDecimal orderPrice = orderEntity.getOrderPrice();
                //商品总价
                BigDecimal goodsPrice = orderEntity.getGoodsPrice();
                //下单时间
                Date addTime = orderEntity.getAddTime();
                //发货时间
                Date deliveryTime = orderEntity.getDeliveryTime();
                //支付时间
                Date payTime = orderEntity.getPayTime();
                //申请退款日期
                Date refundApplyTime = orderEntity.getRefundApplyTime();
                //订单确认收货日期
                Date confirmTime = orderEntity.getConfirmTime();
                //买家留言
                String postscript = orderEntity.getPostscript();
                //卖家备注
                String remark = orderEntity.getRemark();
                //购买的商品
                params.put("orderId", orderEntity.getId());
                List<OrderGoodsEntity> orderGoodsEntities = orderGoodsService.queryList(params);
                StringBuffer sb = new StringBuffer();
                for (OrderGoodsEntity orderGoodsEntity : orderGoodsEntities) {
                    String goodsName = orderGoodsEntity.getGoodsName();
                    String productName = orderGoodsEntity.getProductName();
                    Integer number = orderGoodsEntity.getNumber();
                    sb.append("商品名称：");
                    sb.append(goodsName);
                    sb.append("\r\n");
                    sb.append("产品规格：");
                    sb.append(productName);
                    sb.append("\r\n");
                    sb.append("数量：");
                    sb.append(number);
                    sb.append("\r\n");
                }

                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                // "订单号", "会员微信昵称", "订单状态", "订单付款状态",
                map.put("orderSn", orderSn);
                map.put("nickname", nickname);
                map.put("orderStatusText", orderStatusText);
                map.put("payStatusText", payStatusText);

                // "快递状态", "收货人", "收货地址", "联系电话",
                map.put("shippingStatusText", shippingStatusText);
                map.put("consignee", consignee);
                map.put("address", address);
                map.put("mobile", mobile);

                //"快递公司", "快递单号", "快递费用", "实际支付",
                map.put("shippingName", shippingName);
                map.put("shippingNo", shippingNo);
                map.put("shippingFee", shippingFee);
                map.put("actualPrice", actualPrice);

                //"订单总价", "商品总价", "下单时间", "发货时间",
                map.put("orderPrice", orderPrice);
                map.put("goodsPrice", goodsPrice);
                map.put("addTime", addTime);
                map.put("deliveryTime", deliveryTime);

                //"支付时间", "申请退款日期", "订单确认收货日期", "购买商品"};
                map.put("payTime", payTime);
                map.put("refundApplyTime", refundApplyTime);
                map.put("confirmTime", confirmTime);
                map.put("goodsList", sb.toString());

                //买家留言，卖家备注
                map.put("postscript", postscript);
                map.put("remark", remark);

                list.add(map);
            }
        }

        ee.addSheetByMap("订单列表", list, header);
        ee.export(response);
        return R.ok();
    }

    @RequestMapping("/piLiangSendGoods")
    @RequiresPermissions("order:piLiangSendGoods")
    public R piLiangSendGoods(@RequestBody OrderEntity[] orderList) {

        for (OrderEntity orderEntity : orderList) {
            String orderSn = orderEntity.getOrderSn();
            String shippingNo = orderEntity.getShippingNo();
            Integer shippingId = orderEntity.getShippingId();
            if (orderSn != null && shippingNo != null) {
                orderEntity.setShippingId(shippingId);
                ShippingEntity shippingEntity = shippingService.queryObject(shippingId);
                String shippingName = "";
                if (shippingEntity != null) {
                    shippingName = shippingEntity.getName();
                }
                orderEntity.setShippingName(shippingName);
                orderEntity.setShippingNo(shippingNo);
                orderService.sendGoods(orderEntity);
            }
        }

        return R.ok();
    }


    /**
     * 列表
     */
    @RequestMapping("/shippingList")
    public R shippingList(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        query.put("orderStatus", "201");
        query.put("payStatus", "2");
        query.put("shippingStatus", "0");
        query.put("sidx", "id");
        query.put("order", "desc");

        List<OrderEntity> orderList = orderService.queryList(query);
        if (orderList.size() > 0) {
            for (OrderEntity orderEntity : orderList) {
                Integer userId = orderEntity.getUserId();
                UserEntity userEntity = userService.queryObject(userId);
                if (userEntity != null) {
                    userEntity.setNickname(EmojiUtils.emojiRecovery2(userEntity.getNickname()));
                }
                orderEntity.setUserEntity(userEntity);
            }
        }

        int total = orderService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 列表
     */
    @RequestMapping("/refundList")
    public R refundList(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        query.put("payStatus", "4");
        query.put("sidx", "refund_apply_time");
        query.put("order", "desc");

        List<OrderEntity> orderList = orderService.queryList(query);
        if (orderList.size() > 0) {
            for (OrderEntity orderEntity : orderList) {
                Integer userId = orderEntity.getUserId();
                UserEntity userEntity = userService.queryObject(userId);
                if (userEntity != null) {
                    userEntity.setNickname(EmojiUtils.emojiRecovery2(userEntity.getNickname()));
                }
                orderEntity.setUserEntity(userEntity);
            }
        }

        int total = orderService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("order:info")
    public R info(@PathVariable("id") Integer id) {
        OrderEntity order = orderService.queryObject(id);
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", id);
        List<OrderGoodsEntity> orderGoodsEntities = orderGoodsService.queryList(params);
        order.setOrderGoodsList(orderGoodsEntities);

        return R.ok().put("order", order);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("order:save")
    public R save(@RequestBody OrderEntity order) {
        orderService.save(order);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("order:update")
    public R update(@RequestBody OrderEntity order) {
        orderService.update(order);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("order:delete")
    public R delete(@RequestBody Integer[] ids) {
        orderService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<OrderEntity> list = orderService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 总计
     */
    @RequestMapping("/queryTotal")
    public R queryTotal(@RequestParam Map<String, Object> params) {
        int sum = orderService.queryTotal(params);

        return R.ok().put("sum", sum);
    }

    /**
     * 确定收货
     *
     * @param id
     * @return
     */
    @RequestMapping("/confirm")
    @RequiresPermissions("order:confirm")
    public R confirm(@RequestBody Integer id) {
        return orderService.confirm(id);
    }

    /**
     * 发货
     *
     * @param order
     * @return
     */
    @RequestMapping("/sendGoods")
    @RequiresPermissions("order:sendGoods")
    public R sendGoods(@RequestBody OrderEntity order) {

        return orderService.sendGoods(order);
    }

    @RequestMapping("getOrderTraces")
    public R getOrderTraces(Integer id) {
        OrderEntity order = orderService.queryObject(id);
        Integer shippingId = order.getShippingId();
        ShippingEntity shippingEntity = shippingService.queryObject(shippingId);
        List orderTracesByJson = KuaiDiUtils.getOrderTracesByJson(shippingEntity.getCode(), order.getShippingNo());
        Collections.reverse(orderTracesByJson);
        return R.ok(orderTracesByJson);
    }

    /**
     * 同意退款
     *
     * @param id
     * @return
     */
    @RequestMapping("agreeRefund")
    @RequiresPermissions("order:agreeRefund")
    public R agreeRefund(Integer id) {
        OrderEntity order = orderService.queryObject(id);
        Integer orderStatus = order.getOrderStatus();
        if (!(orderStatus == 401 || orderStatus == 402)) {
            return R.error("该订单非申请退款状态");
        }

        BigDecimal actualPrice = order.getActualPrice();
        Map<String, String> params = new HashMap<>();
        //公众账号ID
        params.put("appid", appid);
        //商户号
        params.put("mch_id", partner);
        params.put("out_trade_no", order.getOutTradeNo());
        //商户订单号
        params.put("out_refund_no", System.currentTimeMillis() + "");
        //订单金额
        params.put("total_fee", String.valueOf((((int) (actualPrice.floatValue() * 100)))));
        //退款金额
        params.put("refund_fee", String.valueOf((((int) (actualPrice.floatValue() * 100)))));
        //退款结果通知url
        params.put("notify_url", refund_url);

        Map<String, String> refund = PaymentApi.refund(params, paternerKey, certPath);

        System.out.println("refund:" + refund);

        String resultCode = refund.get("result_code");

        if (resultCode == null) {
            return R.error("系统错误，请联系管理员");
        }

        if ("FAIL".equals(resultCode)) {
            return R.error(refund.get("err_code_des"));
        }
        /*
        订单状态
        1xx 表示订单取消和删除等状态 0订单创建成功等待付款，　101订单已取消，　102订单已删除
        2xx 表示订单支付状态　201订单已付款，等待发货
        3xx 表示订单物流相关状态　300订单已发货， 301用户确认收货
        4xx 表示订单退换货相关的状态　401 没有发货，退款　402 已收货，退款退货
        */

        //付款状态 支付状态;0未付款;1付款中;2已付款;4退款
        order.setPayStatus(4);
        if (orderStatus == 402) {
            order.setShippingStatus(4);
        }
        order.setOrderStatus(403);
        orderService.update(order);
        //退款操作

        return R.ok("");
    }

    /**
     * 拒绝退款
     *
     * @param id
     * @return
     */
    @RequestMapping("refuseRefund")
    @RequiresPermissions("order:refuseRefund")
    public R refuseRefund(Integer id, String refundRefuseReson) {
        OrderEntity order = orderService.queryObject(id);
        Integer orderStatus = order.getOrderStatus();
        if (!(orderStatus == 401 || orderStatus == 402)) {
            return R.error("该订单非申请退款状态");
        }
        order.setOrderStatus(404);
        order.setRefundRefuseReson(refundRefuseReson);
        orderService.update(order);

        WxaConfig wxaConfig = new WxaConfig();
        wxaConfig.setAppId(ResourceUtil.getConfigByName("wx.appId"));
        wxaConfig.setAppSecret(ResourceUtil.getConfigByName("wx.secret"));
        WxaConfigKit.setWxaConfig(wxaConfig);
        WxaTemplateApi wxaTemplateApi = Duang.duang(WxaTemplateApi.class);
        WxaTemplate template = new WxaTemplate();
        //支付的prepay_id
        template.setForm_id(order.getPayId());
        UserEntity userEntity = userService.queryObject(order.getUserId());
        //接收者（用户）的 openid
        template.setTouser(userEntity.getWeixinOpenid());
        //购买成功通知的模板ID
        template.setTemplate_id("9x-YJZk7BTJF4NFyknuZFAZckiMIad-SndIxvlPYPTo");
        //小程序调转的页面:订单详情
        template.setPage("pages/orderDetail/orderDetail?orderId=" + order.getId());
        //订单号
        template.add("keyword1", order.getOrderSn());
        //退款金额
        template.add("keyword2", order.getActualPrice().toString());
        //退款理由
        template.add("keyword3", refundRefuseReson);
        String build = template.build();
        ApiResult send = wxaTemplateApi.send(build);
        Integer errorCode = send.getErrorCode();
        if (errorCode != 0) {
            System.out.println("模板发送失败信息：" + send.getErrorMsg());
        }
        System.out.println("模板信息发送成功");


        return R.ok("");
    }

}
